package com.indiv.pmy.world;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public abstract class World2d extends JFrame implements Runnable {
	
	Thread worldThread;
	Container container;
	WorldPanel worldPanel;
		
	Color background = Color.darkGray;
	
	public World2d(int width, int height, String title) {
		super(title);
		setSize(width+15, height+15);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new FlowLayout());
		worldPanel = new WorldPanel();
		worldPanel.setPreferredSize(new Dimension(width,height));
		setContentPane(worldPanel);
		setVisible(true);

		init();
	}
	
	public World2d() {
		super("World2d");
		setSize(115,115);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new FlowLayout());
		worldPanel = new WorldPanel();
		worldPanel.setPreferredSize(new Dimension(100,100));
		setContentPane(worldPanel);
		setVisible(true);

		init();
	}
	
	public void setBackgroundColor(Color c) {
		worldPanel.setBackground(c);
	}
	
	public abstract void init();
	public abstract void update();
	public abstract void render(Graphics g);
	public void start() {
		worldThread = new Thread(this);
		System.out.println("Starting world thread...");
		worldThread.start();
	}
	public void run() {
		while(true) {
			update();
			worldPanel.repaint();
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void stop() {
		worldThread.interrupt();
	}
	
	public class WorldPanel extends JPanel {
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			render(g);
		}
	}
}